/**
 * Created by Administrator on 2017/9/16.
 */

import Vue from 'vue'
import Vuex from 'vuex'
import {SET_MSG,SET_MINAGE,APPEND_STUDENT} from './mutationNames'

Vue.use(Vuex)

//定义state
const state = {
    message: 'Default msg here!',
    minAge: 0,
    students: [{
        name: 'Leo',
        age: 20
    }, {
        name: 'Linda',
        age: 40
    },{
        name: 'Jack',
        age: 25
    },{
        name: 'Tom',
        age: 50
    },]
}

//定义getters -- 相当于Store的计算属性
const getters = {
    msg: state=>state.message,
    students: function (state) {
        return state.students;
    },
    countOfStudents: function (state, getters) {
        return getters.students.length
    },
    oldStudents: function (state) {
        return state.students.filter(s=>s.age > state.minAge);
    }
}

//Mutations
//作用：调用 store.commit 方法，更改 Vuex 的 store 中的状态的唯一方法
const mutations = {
    [SET_MSG]: function (state, msg) {
        state.message = msg;
    },
    [SET_MINAGE]: function (state, minAge) {
        this.minAge = minAge;
    },
    [APPEND_STUDENT]: function (state, student) {
        state.students.push(student)
    }
}

//Actions
//作用：1.提交的是 mutation，而不是直接变更状态
//     2.可以包含任意异步操作
const actions = {
    setMsg: function ({commit}, msg) {
        console.log('Sync setMsg is called')
        commit(SET_MSG, msg)
    },
    setMsgAsync: function ({commit}, msg) {
        console.log('Async setMsg is called')
        let self = this;
        return new Promise((resolve, reject)=>{
            setTimeout(function () {
                self.dispatch('setMsg', msg)
                resolve()
            },1000)
        });
    }
}

//导出Store
export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
});